from flask import Flask, request, jsonify, abort
import pymongo,json
import music163_search
from Token import certify_token,generate_token
from app.common import commonAPI
app = Flask(__name__)
# 注册蓝图
app.register_blueprint(commonAPI)

# 03397FD3D3DB7947 bjfu md5
client = pymongo.MongoClient(host='127.0.0.1', port=27017)
app.config['JSON_AS_ASCII'] = False
db = client.realtime
no_Auth = ['/getpublickey','/login']


@app.route("/music/<string:title>", methods=['POST', 'GET'])
def search_music(title):
    # rev = request.get_json()['title']
    result_list = []
    collections = db.musicdb
    res = {}
    if title == "":
        abort()
        return
    results = collections.find({"title": {"$regex": title, "$options": "i"}}, {"_id": 0})
    for result in results:
        # print(result)
        collections = db.copyrightdb
        results = collections.find({"title": {"$regex": title, "$options": "i"}}, {"_id": 0})
        for result in results:
            # print(result)
            result_list.append(result)
        # code = {"code": 200}
        # result_list.append(code)
        res = result_list
        # result_list[0] = "code":"200"
        return jsonify(res)
    res = music163_search.search(title)
    # result_list = music163_search.search(title)
    # code = {"code": 200}
    # result_list.append(code)
    # results['code'] = '200'
    return jsonify(res)


# 请求拦截器
@app.before_request
def before():
    """
       针对app实例定义全局拦截器
       """
    url = request.path  # 读取到当前接口的地址
    header = request.headers
    isExpred= certify_token(header.get('Authorization',''))
    if url in no_Auth: #拦截不需要验证的接口
        pass
    elif isExpred is False:
        return {
            'code': -9998,
            'data': '',
            'msg': '登陆时间过期，请重新登录'
        }
    else:
        pass


@app.after_request
def after(res):
    url = request.path  # 读取到当前接口的地址
    data = {
        'code':20000,
        'datas':res.get_json(),
        'message':'成功'
    }
    res.data = json.dumps(data).encode()
    if url == '/login' and url not in no_Auth:# 单独处理登录接口
        res.headers['Authorization'] = generate_token()
    else: #拦截不需要验证的接口
        pass
    # else:
    #     res.headers['Authorization'] = generate_token()
    # return 响应体, 状态码, 响应头
    return res

@app.errorhandler(Exception)
def catch_all_except(e):
    data = {
        'code': -9999,
        'datas':'',
        'message': '失败'
    }
    print(e)
    return jsonify(data)
# if __name__ == '__main__':
#     app.run(host='127.0.0.1', port=5000)
